import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import * as API from '../api/https'
const initialState = {
    shoplist: []
}
const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: {
        getshoplist(state, action) {
            state.shoplist = action.payload
        },
        getaddshoplist(state, action) {
            state.shoplist.push(action.payload)
        },
        geteaitshoplist(state, action) {
            let i = state.shoplist.findIndex(item => {
                return item.id == action.payload.id
            })
            state.shoplist[i] = action.payload
        },
        getdelshoplist(state, action) {
            state.shoplist = state.shoplist.filter(item => {
                return item.id !== action.payload
            })
        }
    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;
export let async_getshoplist = createAsyncThunk('async_getshoplist',
    async (_, store) => {
        let res = await API.httpgetshoplist()
        store.dispatch(actionfn.getshoplist(res))
    })
export let async_getaddshoplist = createAsyncThunk('async_getaddshoplist',
    async (obj, store) => {
        let res = await API.httpaddshoplist(obj)
        store.dispatch(actionfn.getaddshoplist(res))
    })
export let async_geteaitshoplist = createAsyncThunk('async_geteaitshoplist',
    async (obj, store) => {
        let res = await API.httpeaitshoplist(obj)
        store.dispatch(actionfn.geteaitshoplist(res))
    })
export let async_getdelshoplist = createAsyncThunk('async_getdelshoplist',
    async (id, store) => {
        await API.httpdelshoplist(id)
        store.dispatch(actionfn.getdelshoplist(id))
    })
export let async_searchshoplist = createAsyncThunk('async_searchshoplist',
    async (title, store) => {
        let res = await API.httpsearchshoplist(title)
        store.dispatch(actionfn.getshoplist(res))
    })